package cn.net.wanji.utils;

import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;
import java.util.ArrayList;
import java.util.List;

@Slf4j(topic = "寻找磁盘挂载目录判断磁盘占比【DiskUtils】")
public class DiskUtils {
    private final static Logger diskFileLogger = LoggerFactory.getLogger("file");
    public static void main(String[] args) {
        String filePath = "D:\\project";
//        getMountPointAndDiskUsage(filePath);
        String nextLevelPath = getNextLevelPath(filePath);
        System.out.println(nextLevelPath);
    }

    public static Double getMountPointAndDiskUsage(String filePath) {
        if (isMountPoint(filePath)) {
            double diskUsage = getDiskUsage(filePath);
//            diskFileLogger.info("磁盘挂载路径：" + filePath);
//            diskFileLogger.info("磁盘占比：" + diskUsage + "%");
            return diskUsage;
        } else {
//            diskFileLogger.info("getNextLevelPath：" + filePath);
            String nextLevelPath = getNextLevelPath(filePath);
            if (nextLevelPath != null) {
                Double mountPointAndDiskUsage = getMountPointAndDiskUsage(nextLevelPath);
                return mountPointAndDiskUsage;
            } else {
                diskFileLogger.info("无法找到挂载磁盘路径。"+nextLevelPath);
                return 0.0;

            }
        }
    }

    private static boolean isMountPoint(String path) {
            List<String> list = new ArrayList<>();
            list.add("df " + path);
            List<String> strings = executeNewFlow(list);
            for (String string : strings) {
                if (StringUtils.isNotNull(string)&&string.contains(path)) {
                    diskFileLogger.info("磁盘挂载路径：" + path);
                    return true;
                }
            }
//            diskFileLogger.info("executeNewFlow： ",strings);
        return false;
    }

    private static double getDiskUsage(String path) {
            List<String> list = new ArrayList<>();
            list.add("df -h " + path);
            List<String> strings = executeNewFlow(list);
            for (String string : strings) {
                if (StringUtils.isNotNull(string)&&string.contains(path)) {
                    String[] fields = string.split("\\s+");
                    String usageField = fields[fields.length - 2];
                    String substring = usageField.substring(0, usageField.length() - 1);
                    String sb = usageField.replace("%", "");
                    return Double.parseDouble(substring);
                }
            }
        return 0.0;
    }

    private static String getNextLevelPath(String filePath) {
        File file = new File(filePath);
        if (file.getParent() != null) {
            return file.getParent();
        }
        return null;
    }

    /**
     * 运行Linux命令
     *
     * @param commands 命令集合
     * @return 返回结果
     * @author YuanRiKang
     * @date 2022/5/24 16:56
     */
    private static List<String> executeNewFlow(List<String> commands) {
        List<String> rspList = new ArrayList<>();
        Runtime run = Runtime.getRuntime();
        try {
            Process proc = run.exec("/bin/bash", null, null);
            BufferedReader in = new BufferedReader(new InputStreamReader(proc.getInputStream()));
            PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(proc.getOutputStream())), true);
            for (String line : commands) {
                out.println(line);
            }
            out.println("exit");// 这个命令必须执行，否则in流不结束。
            String rspLine = "";
            while ((rspLine = in.readLine()) != null) {
//                System.out.println(rspLine);
                rspList.add(rspLine);
            }
            proc.waitFor();
            in.close();
            out.close();
            proc.destroy();
        } catch (IOException | InterruptedException e1) {
            e1.printStackTrace();
        }
        return rspList;
    }
}

